import { asyncRoutes, constantRoutes } from '@/router'

/**
 * 校验路由的path是否在数组中，在即有权限
 * @param paths
 * @param route
 * @returns {Boolean}
 */
function hasPermission(paths, route) {
  return route.hidden || paths.includes(route.path)
}

/**
 * 过滤路由
 * @param routes
 * @param paths
 */
export function filterAsyncRoutes(routes, paths) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(paths, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, paths)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, paths) {
    return new Promise(resolve => {
      let accessedRoutes
      //*表示全部菜单
      if (paths.length === 1 && paths[0] === '*') {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, paths)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
